package com.example.networkinteraction.api;

import com.example.networkinteraction.manager.UrlManager;
import com.example.networkinteraction.retrofit.RetrofitBuilder;
import okhttp3.OkHttpClient;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

import java.util.HashMap;

public enum ApiFactory {
    INSTANCE;
    private static HashMap<String, Object> sApiServiceCache = new HashMap<>();

    private CallAdapter.Factory[] callAdapterFactory;

    private Converter.Factory[] converterFactory;

    private OkHttpClient okHttpClient;

    public static ApiFactory getInstance() {
        return INSTANCE;
    }

    public ApiFactory setBaseUrl(String baseUrl) {
        UrlManager.getInstance().setUrl(baseUrl);
        return this;
    }

    public void clearAllApi() {
        sApiServiceCache.clear();
    }

    public ApiFactory setCallAdapterFactory(CallAdapter.Factory... callAdapterFactory) {
        this.callAdapterFactory = callAdapterFactory;
        return this;
    }

    public ApiFactory setConverterFactory(Converter.Factory... converterFactory) {
        this.converterFactory = converterFactory;
        return this;
    }

    public ApiFactory setOkClient(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
        return this;
    }

    /**
     * 创建接口API
     *
     * @param apiCls 接口类
     * @param <A>    具体类型
     * @return 具体类型
     */
    public <A> A createApi(Class<A> apiCls) {
        UrlManager manager = UrlManager.getInstance();
        String defaultUlrKey = manager.getDefaultUrlKey();
        return createApi(defaultUlrKey, manager.getUrl(defaultUlrKey), apiCls);
    }

    /**
     * 创建接口API
     * 可以更改API地址
     *
     * @param baseUrlKey
     * @param baserUrlValue
     * @param apiCls
     * @param <A>
     * @return
     */
    public <A> A createApi(String baseUrlKey, String baserUrlValue, Class<A> apiCls) {
        String key = getApiKey(baseUrlKey, apiCls);
        A api = (A) sApiServiceCache.get(key);
        if (null == api) {
            Retrofit retrofit = new RetrofitBuilder()
                    .setBaseUrl(baserUrlValue)
                    .setCallAdapterFactory(callAdapterFactory)
                    .setConvertFactory(converterFactory)
                    .setOkHttpClient(okHttpClient)
                    .builder();
            api = retrofit.create(apiCls);
            sApiServiceCache.put(baseUrlKey, api);
        }
        return api;
    }

    private <A> String getApiKey(String baseUrlKey, Class<A> apiCls) {
        return String.format("%s_%s", baseUrlKey, apiCls);
    }
}